<?php

/**
 * Utility functions.
 *
 * @author Pascal de Vink
 */

/**
 * Returns value from array or default value if array doesn't contain entry with given name.
 *
 * @param array $array Array to check
 * @param string $key Key to search in array
 * @param mixed $default Default value if key doesn't exist in array
 * @return mixed Value in array or default if key doesn't exist in arrays
 */
function array_get(&$array, $key, $default) {
	return isset($array[$key])? $array[$key] : $default;
}

/**
 * Returns array where given prefix has been stripped from each array key.
 *
 * @param string $prefix Prefix to remove from each array key.
 * @param array $array Array to check
 * @return array Array with each key stripped.
 */
function &array_strip($prefix, &$array) {
	if (!$array) return $array;
	
	$new_array = array();
	$len = strlen($prefix);
	foreach ($array as $key => $value) {
		if (substr($key, 0, $len) == $prefix) {
			$new_array[substr($key, $len)] = $value;
		} else {
			$new_array[$key] = $value;
		}
	}
	return $new_array;
}

/**
 * Checks if string contains only numerics (not dot, characters, etc.)
 *
 * Note: standard routine is_numeric also accepts "1.1"
 *
 * @param string $var String to check
 */
function check_numeric($var){
	return ctype_digit($var);
}



function dom_to_simple_array($domnode, &$array) {
  $array_ptr = &$array;
  $domnode = $domnode->firstChild;
  while (!is_null($domnode)) {
   if (! (trim($domnode->nodeValue) == "") ) {
     switch ($domnode->nodeType) {
       case XML_TEXT_NODE: {
         $array_ptr['cdata'] = $domnode->nodeValue;
         break;
       }
       case XML_ELEMENT_NODE: {
         $array_ptr = &$array[$domnode->nodeName][];
         if ($domnode->hasAttributes() ) {
           $attributes = $domnode->attributes ();
           if (!is_array ($attributes)) {
             break;
           }
           foreach ($attributes as $index => $domobj) {
             $array_ptr[$index] = $array_ptr[$domobj->name] = $domobj->value;
           }
         }
         break;
       }
     }
     if ( $domnode->hasChildNodes() ) {
       dom_to_simple_array($domnode, $array_ptr);
     }
   }
   $domnode = $domnode->nextSibling;
  }
}

/**
 * Returns file extension.
 *
 * @param string $path Path to file including file extension
 * @return string File extension (without '.') or NULL if no file extension
 */
function file_extension($path) {
	$pos = strrpos($path, '.');
	if (!$pos) return NULL;
	
	$ext = substr($path, $pos+1);
	if (substr($ext, 0, 1) == '/' || strpos($ext, '/')) return NULL;
	if (substr($ext, 0, 1) == '\\' || strpos($ext, '\\')) return NULL;
	
	return $ext;	
}

/**
 * Returns file name.
 *
 * @param string $path Path to file including file extension
 * @return string File name or NULL if no file name
 */
function file_name($path) {
	$pos = strrpos($path, '/');
	if ($pos >= 0) $path = substr($path, $pos+1);
	
	$pos = strrpos($path, '.');
	if ($pos == false) return $path;
	if ($pos == 0) return NULL;
	return substr($path, 0, $pos);
}

/**
 * Checks if include file exists.
 *
 * @param string $inc Relative path for include file
 */
function include_exists($inc) {
	foreach (explode(';', ini_get('include_path')) as $path) {
		foreach (explode(':', $path) as $path2) {
			if (file_exists($path2 . '/' . $inc)) return true;
		}
	}
	return false;
}

/**
 * Prints given string followed by <br> tag.
 *
 * @param string $str String to be printed.
 */
function println($str) {
	print($str);
	print("<br>\n");
}

/**
 * Recursively prints contents of parameter surrounded by <pre>...</pre>.
 *
 * @param mixed $par Parameter to be printed.
 */
function printr(&$par) {
	print("<pre>");
	print_r($par);
	print("</pre>");
}

/**
 * Initializes random generatior
 */
function random_init() {
	static $rand_called = FALSE;
	if (!$rand_called) {
		srand((double) microtime() * 1000000);
		$rand_called = TRUE;
	}
}

/**
 * Return random number in given range (initializes on first call).
 *
 * @param int $low Lowerbound for random number
 * @param int $high Upperbound for random number
 * @return int Random number
 */
function random_number($low, $high) {
	random_init();
	return rand($low, $high);
	return $rNum;
} 

/**
 * Returns random string with given length (using given character set)
 *
 * @param int $length Length of random string
 * @param string $set Set of characters from which to composed random string
 * @return string Random string
 */
function random_string($length, $set = "01234567890ABCDEF") {
	$set_length = strlen($set);
	random_init();
	for ($i = 0; $i < $length; $i++) {
		$str .= substr($set, rand() % $set_length, 1);
	}
	return $str;
}

/**
 * Prefixes every uppercase character with underscore, except for the first character,
 * and converts string to lowercase.
 *
 * Example: MyNameIsSilvain => my_name_is_silvain
 *
 * @param string $str String to be converted.
 * @return string Converted string
 */
function str_add_underscores($str) {
	return strtolower(substr($str, 0, 1) . preg_replace('/[A-Z]/', '_\\0', substr($str, 1)));
}

/**
 * Replaces every character following an underscore with the corresponding 
 * uppercase character including the first character, and removes all underscores. 
 *
 * Example: my_name_is_silvain => MyNameIsSilvain
 *
 * @param string $str String to be converted.
 * @return string Converted string
 */
function str_remove_underscores($str) {
	if (substr($str, 0, 1) == '_') $str = substr($str, 1);
	if (substr($str, -1) == '_') $str = substr($str, 0, -1);
	return strtoupper(substr($str, 0, 1)) . preg_replace('/_([a-z])/e', "strtoupper('\\1')", substr($str, 1));
}

/**
 * Replaces special chars with UNICODE codes
 *
 * @param string $content Content to be replaced
 * @param string $escape_char Escape character used to prefix UNICODE codes
 * @return string Replaced content.
 */
function encode_special_chars($content, $escape_char = "&") {

	# find special chars
	$char_ords = count_chars($content, 1);
	foreach ($char_ords as $char_ord => $char_freq) {
		if (   ($char_ord >= 32 && $char_ord <= 127) # regular ascii
			|| $char_ord == 9 # TAB
			|| ($char_ord >= 10 && $char_ord <= 13) # CR/LF
		   ) continue;
		
		# replace special char
		$new_char_encoded = $escape_char . "#" . $char_ord . ";";
		$content = str_replace(chr($char_ord), $new_char_encoded, $content);
	}
	return $content;
}

	function convertBool($bool, $to = 'text', $lang = 'NL'){
		
		switch ($to){
			
			case 'text':
			
				if ($lang == 'ENG' && ($bool == 'y' || $bool == 'true' || $bool == 'ja' || $bool == '1')) {
					$output = 'yes';
				}
				elseif ($lang == 'ENG' && ($bool == 'n' || $bool == 'false' || $bool == 'nee'|| $bool == '0')) {
					$output = 'no';
				}
				elseif ($lang == 'NL' && ($bool == 'y' || $bool == 'true' || $bool == 'yes'|| $bool == '1')) {
					$output = 'ja';
				}
				elseif ($lang == 'NL' && ($bool == 'n' || $bool == 'false' || $bool == 'no'|| $bool == '0')) {
					$output = 'nee';
				}else {			
					$output = 'false';			
				}
			
			break;
			
			case 'trueorfalse':
			
				if ($bool == 'y' || $bool == 'yes' || $bool == 'ja' || $bool == '1') {
					$output = 'true';
				}
				elseif ($bool == 'n' || $bool == 'no' || $bool == 'nee'|| $bool == '0' || $bool == '') {
					$output = 'false';
				}else {			
					$output = 'false';			
				}
			break;
			
			case 'number':
			
				if ($bool == 'y' || $bool == 'yes' || $bool == 'ja' || $bool == 'true') {
					$output = '1';
				}
				elseif ($bool == 'n' || $bool == 'no' || $bool == 'nee' || $bool == 'false') {
					$output = '0';
				}else {			
					$output = 'false';			
				}		
			break;
			
			
		}
		
		return $output;
		
	}
	
	function toMySQLdate($date){
			
		$jaar 	= substr($date,0,4);
		$maand	= substr($date,4,2);
		$dag	= substr($date,6,2);
		
		$mysqldate = $jaar."-".$maand."-".$dag;
			
		if (strlen($date) > 8) {
			$uren	= substr($date,8,2);
			$min	= substr($date,10,2);
			$sec	= substr($date,12,2);
				
		$mysqldate = $mysqldate." ".$uren.":".$min.":".$sec;
		
		}

		return  $mysqldate	;
		
	}
	
	function listfiles($__dir="./",$__pattern="*.*"){
		settype($__dir,"string");
		settype($__pattern,"string");
		
		$__ls=array();
		$__regexp=preg_quote($__pattern,"/");
		$__regexp=preg_replace("/[\\x5C][\x2A]/",".*",$__regexp);
		$__regexp=preg_replace("/[\\x5C][\x3F]/",".", $__regexp);
		
		if(is_dir($__dir))
			if(($__dir_h=@opendir($__dir))!==FALSE)	{
				while(($__file=readdir($__dir_h))!==FALSE)
					if(preg_match("/^".$__regexp."$/",$__file))						
					
						array_push($__ls,$__file);
		
						closedir($__dir_h);
						sort($__ls,SORT_STRING);
					}
		 return $__ls;
	}
		
	function parsed_listing($list, $systype)
	{
		$i = 0;
	
		foreach ($list as $current) {
		switch ($systype) {
			case "Windows_NT":
				ereg("([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|<DIR>) +(.+)",$current,$split);
				if (is_array($split)) {
					if ($split[3]<70) { $split[3]+=2000; } else { $split[3]+=1900; } // 4digit year fix
						$parsed[$i]['isdir'] = ($split[7]=="<DIR>");
						$parsed[$i]['size'] = $split[7];
						$parsed[$i]['month'] = $split[1];
						$parsed[$i]['day'] = $split[2];
						$parsed[$i]['time/year'] = $split[3];
						$parsed[$i]['name'] = $split[8];
						$i++;
		         }
		         break;
			case "UNIX":
			default:
				$split = preg_split("[ ]", $current, 9, PREG_SPLIT_NO_EMPTY);
				if ($split[0] != "total") {
					$parsed[$i]['isdir']        = $split[0]{0} === "d";
					$parsed[$i]['perms']        = $split[0];
					$parsed[$i]['number']    = $split[1];
					$parsed[$i]['owner']        = $split[2];
					$parsed[$i]['group']        = $split[3];
					$parsed[$i]['size']        = $split[4];
					$parsed[$i]['month']        = $split[5];
					$parsed[$i]['day']        = $split[6];
					$parsed[$i]['time/year']    = $split[7];
					$parsed[$i]['name']        = $split[8];
					$i++;
				}
		        break;
	     }
	   }
	   return $parsed;
	}

	function debug($info){
		// Alleen zichtbaar als onderstaande regel waar is.
		if ($_SESSION[debug] == 'y' && ($_SESSION[uretail][user_name] == 'gerard' or $_SESSION[uretail][user_name] == 'gerritjan')) {
			dump($info);
		}
	}


	function array_encode($array){
		if(is_array($array)){
			foreach($array as $key=>$element){
				if(is_array($element)){
					$array[$key] = array_encode($element);
				}else{
					$array[$key] = mysql_real_escape_string($element);	
				}
			}	
		}else{
			$array = mysql_real_escape_string($array);
		}
		return $array;
	}
	
	function array_stripslashes($array){
		if(is_array($array)){
			foreach($array as $key=>$element){
				if(is_array($element)){
					$array = array_stripslashes ($element );
				}else{
					$array[$key] = stripslashes($element);
				}
			}	
		}else{
			$array = stripslashes($array);
		}
		return $array;
	}
?>